<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点日期">
        <el-date-picker size="mini"
                        v-model="daterangePdTime"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="盘点人" prop="pdName">
        <el-input size="mini"
                  v-model="queryParams.pdName"
                  placeholder="请输入盘点人"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点备注" prop="pdBz">
        <el-input size="mini"
                  v-model="queryParams.pdBz"
                  placeholder="请输入盘点备注"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wzgl:wzpd:add']"
        >新增盘点单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wzgl:wzpd:edit']"
        >修改盘点单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wzgl:wzpd:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wzgl:wzpd:export']"
        >导出Excel
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          icon="el-icon-upload2"-->
      <!--          size="mini"-->
      <!--          @click="handleImport"-->
      <!--          v-hasPermi="['wzgl:wzpd:import']"-->
      <!--        >导入</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="wzpdList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="盘点详情" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handlePdXqClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="盘点日期" align="center" prop="pdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点人" align="center" prop="pdName" width="180"/>
      <el-table-column label="所属部门" align="center" prop="deptName" width="180"/>
      <el-table-column label="盘点备注" align="center" prop="pdBz"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wzgl:wzpd:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wzgl:wzpd:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 导入对话框 -->
    <vxe-modal :title="upload.title" v-model="upload.open" width="400px" showFooter show-zoom resize>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 添加或修改物资盘点对话框 -->
    <vxe-modal :title="title" v-model="open" width="90%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">盘点基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="5">
              <el-form-item label="盘点日期" prop="pdTime">
                <el-date-picker clearable style="width: 100%;"
                                v-model="form.pdTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择盘点日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="盘点人" prop="pdName">
                <el-input v-model="form.pdName" placeholder="请输入盘点人"/>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="盘点备注" prop="pdBz">
                <el-input v-model="form.pdBz" placeholder="请输入盘点备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">盘点明细信息</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWzpdPdmx">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWzpdPdmx">删除</el-button>
            </el-col>
          </el-row>
          <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    height="45vh" :data="wzpdPdmxList" :row-class-name="rowWzpdPdmxIndex"
                    @selection-change="handleWzpdPdmxSelectionChange" ref="wzpdPdmx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column v-if="1 === 2" label="物资信息ID" prop="wzxxId" width="150"/>
            <el-table-column show-overflow-tooltip align="center" label="物资名称" prop="wzName">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleButtonClick(scope.row)"
                >
                  <el-link style="font-weight: 600" type="primary">{{ scope.row.wzName }}</el-link>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" label="物资单位" prop="wzDw"/>
            <el-table-column show-overflow-tooltip align="center" label="仓库名称" prop="ckName"/>
            <el-table-column show-overflow-tooltip align="center" label="货架名称" prop="hjName"/>
            <el-table-column show-overflow-tooltip align="center" label="分层名称" prop="fcName"/>
            <el-table-column show-overflow-tooltip align="center" label="物资分类" prop="wzFl"/>
            <el-table-column show-overflow-tooltip align="center" label="物资规格" prop="wzGg"/>
            <el-table-column show-overflow-tooltip align="center" label="物资专业" prop="wzZy"/>
            <el-table-column show-overflow-tooltip align="center" label="单价" prop="dj"/>
            <el-table-column align="center" label="清查数量">
              <el-table-column align="center" label="账面">
                <el-table-column show-overflow-tooltip align="center" label="数量" prop="kc">
                  <template slot-scope="scope">
                    <!--                    <el-input @change="calculateHJJE(scope.$index)" disabled v-model="scope.row.kc" placeholder="请输入账面数量"/>-->
                    <span @change="calculateHJJE(scope.$index)">{{ scope.row.kc }}</span>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip align="center" label="金额" prop="zmJe">
                  <template slot-scope="scope">
                    {{ calculateTotal(scope.row) || '' }}
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="盘点">
              <el-table-column align="center" label="数量" prop="pdSl">
                <template slot-scope="scope">
<!--                  <el-input v-model="scope.row.pdSl"/>-->
                  <span @change="calculateHJJE(scope.$index)">{{ scope.row.kc }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="金额" prop="pdJe">
<!--                <template slot-scope="scope">-->
<!--                  <el-input v-model="scope.row.pdJe"/>-->
<!--                </template>-->
                <template slot-scope="scope">
                  {{ calculateTotal(scope.row) || '' }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="盈" prop="dj">
              <el-table-column align="center" label="数量" prop="ySl">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ySl"/>
                </template>
              </el-table-column>
              <el-table-column align="center" label="金额" prop="yJe">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.yJe"/>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="亏" prop="dj">
              <el-table-column align="center" label="数量" prop="kSl">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.kSl"/>
                </template>
              </el-table-column>
              <el-table-column align="center" label="金额" prop="kJe">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.kJe"/>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="备注" prop="bz" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.bz"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 物资多选 -->
    <WzDuoX ref="wzDuoX"/>

    <!-- 物资详情 -->
    <WzXq ref="wzXq"/>

    <!-- 物资盘点详情 -->
    <WzPdXq ref="wzPdXq"/>
  </div>
</template>

<script>
import {addWzpd, delWzpd, getWzpd, listWzpd, updateWzpd} from "@/api/wzgl/wzpd";
import {getToken} from "@/utils/auth";
import WzDuoX from "@/views/components/WzDuoX/index.vue";
import WzXq from "@/views/wzgl/wzxx/components/WzXq.vue";
import WzPdXq from "@/views/wzgl/wzpd/components/WzPdXq.vue";

export default {
  name: "Wzpd", //物资盘点
  components: {WzPdXq, WzXq, WzDuoX},
  provide() {
    return {
      updateWzLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.wzpdPdmxList.some(existingItem => existingItem.wzxxId === item.wzxxId);
          if (!exists) {
            this.wzpdPdmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWzpdPdmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资盘点表格数据
      wzpdList: [],
      // 盘点明细表格数据
      wzpdPdmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangePdTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pdTime: null,
        pdName: null,
        pdBz: null,
        userId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pdTime: [{required: true, message: "盘点日期不能为空", trigger: "blur"}],
        pdName: [{required: true, message: "盘点人不能为空", trigger: "blur"}],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wzgl/wzpd/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  //监听 kc 的变化
  watch: {
    'wzpdPdmxList': {
      handler(newVal) {
        newVal.forEach((item, index) => {
          this.calculateHJJE(index); // 每当 wzpdPdmxList 发生变化时，计算每个条目的 zmJe
        });
      },
      deep: true // 深度监听，以检测数组内部对象的变化
    }
  },
  methods: {
    //查询物资盘点详情
    handlePdXqClick(row) {
      this.$refs.wzPdXq.handleOpen(row)
    },
    // 查看物资详情信息
    handleButtonClick(row) {
      this.$refs.wzXq.handleOpen(row);
    },
    //将合计金额绑定到表单项
    calculateHJJE(index) {
      const row = this.wzpdPdmxList[index];
      if (row.kc == null) {
        row.zmJe = 0;
        row.pdSl = 0;
      } else {
        row.zmJe = row.dj * row.kc;
        row.pdJe = row.dj * row.kc;
      }
    },
    // 计算合计金额的方法 (只是实时计算并显示, 未绑定)
    calculateTotal(row) {
      if (row.dj && row.kc) {
        return parseFloat(row.dj) * parseFloat(row.kc);
      }
      return '0'; // 当库存为空时，返回0
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询物资盘点列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangePdTime && '' != this.daterangePdTime) {
        this.queryParams.params["beginPdTime"] = this.daterangePdTime[0];
        this.queryParams.params["endPdTime"] = this.daterangePdTime[1];
      }
      listWzpd(this.queryParams).then(response => {
        this.wzpdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wzpdId: null,
        pdTime: null,
        pdName: null,
        pdBz: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.wzpdPdmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePdTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wzpdId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.pdName = this.$store.state.user.name
      this.open = true;
      this.title = "添加物资盘点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const wzpdId = row.wzpdId || this.ids
      getWzpd(wzpdId).then(response => {
        this.form = response.data;
        this.wzpdPdmxList = response.data.wzpdPdmxList;
        this.open = true;
        this.title = "修改物资盘点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wzpdPdmxList = this.wzpdPdmxList;
          if (this.form.wzpdId != null) {
            updateWzpd(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWzpd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wzpdIds = row.wzpdId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delWzpd(wzpdIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 盘点明细序号 */
    rowWzpdPdmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 盘点明细添加按钮操作 */
    handleAddWzpdPdmx() {
      this.$refs.wzDuoX.handleOpen(this.wzpdPdmxList)
      // let obj = {};
      // obj.wzxxId = "";
      // obj.wzName = "";
      // obj.wzDw = "";
      // obj.ckName = "";
      // obj.hjName = "";
      // obj.fcName = "";
      // obj.wzFl = "";
      // obj.wzGg = "";
      // obj.wzZy = "";
      // obj.dj = "";
      // obj.kc = "";
      // obj.zmJe = "";
      // obj.pdSl = "";
      // obj.pdJe = "";
      // obj.ySl = "";
      // obj.yJe = "";
      // obj.kSl = "";
      // obj.kJe = "";
      // obj.bz = "";
      // this.wzpdPdmxList.push(obj);
    },
    /** 盘点明细删除按钮操作 */
    handleDeleteWzpdPdmx() {
      if (this.checkedWzpdPdmx.length == 0) {
        this.$modal.msgError("请先选择要删除的盘点明细数据");
      } else {
        const wzpdPdmxList = this.wzpdPdmxList;
        const checkedWzpdPdmx = this.checkedWzpdPdmx;
        this.wzpdPdmxList = wzpdPdmxList.filter(function (item) {
          return checkedWzpdPdmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWzpdPdmxSelectionChange(selection) {
      this.checkedWzpdPdmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wzgl/wzpd/export', {
        ...this.queryParams
      }, `wzpd_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('wzgl/wzpd/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物资盘点导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
